import 'dart:async';

import 'package:flutter/cupertino.dart';
import 'package:flutterproject/controller/sms_code_controller.dart';
import 'package:flutterproject/mvvm/base/base_controller.dart';
import 'package:flutterproject/util/address_manager.dart';
import 'package:flutterproject/util/dialog_toast/dialog_util.dart';
import 'package:flutterproject/util/dialog_toast/toast_util.dart';
import 'package:flutterproject/util/http/http_client.dart';
import 'package:flutterproject/util/http/http_exception.dart';
import 'package:flutterproject/util/sp_util/shared_preferences.dart';
import 'package:flutterproject/util/sp_util/sp_key.dart';
import 'package:get/get.dart';

class ModifyPayController extends BaseController {
  final TextEditingController codeController = TextEditingController();
  final TextEditingController pwdController = TextEditingController();
  bool isSendCode = false;
  int countDown = 60;
  HttpClient client = Get.find<HttpClient>();
  Timer? _timer;

  Future<bool> resetPwd() async {
    try {
      DialogUtil.showLoading();
      await client.post(AddressManager.updatePayPassword, data: {
        "code": codeController.text,
        "mobile": SPUtils().getString(SPKey.mobile),
        "password": pwdController.text,
      });
      ToastUtil.showSuccess("修改成功!");
      Get.back();
      return true;
    } on HttpException catch (e) {
      ToastUtil.showFailed(e.message);
      return false;
    } finally {
      DialogUtil.dismiss();
    }
  }

  Future<void> sendCode() async {
    if (isSendCode) return;
    final result = await Get.find<SmsCodeController>()
        .sendCode(mobile: SPUtils().getString(SPKey.mobile), type: 6);
    if (!result) return;
    isSendCode = true;
    resetTimer();
    _timer = Timer.periodic(Duration(seconds: 1), (timer) {
      if (countDown == 0) {
        isSendCode = false;
        countDown = 60;
        _timer?.cancel();
        _timer = null;
      }
      countDown--;
      update(['code']);
    });
  }

  void resetTimer() {
    countDown = 60;
    _timer?.cancel();
    _timer = null;
  }

  void onConfirm() {
    if (codeController.text.isEmpty) {
      ToastUtil.showTips("请输入验证码");
      return;
    }
    if (pwdController.text.isEmpty) {
      ToastUtil.showTips("请输入支付密码");
      return;
    }
    resetPwd();
  }
}
